<style lang="less">
@import "./login.less";
</style>

<template>
  <div class="login">
    <div class="login-con">
      <Card icon="log-in" title="欢迎登录" :bordered="false">
        <div class="form-con">
          <login-form @on-success-valid="handleSubmit"></login-form>
          <p @click="GoRegister" class="common f1">立即注册</p>
          <p @click="resetPwd" class="common fr">忘记密码</p>
        </div>
      </Card>
    </div>
  </div>
</template>

<script>
import LoginForm from "_c/login-form";
import { mapActions } from "vuex";
import store from '@/store'
import { setToken } from "@/libs/util";
import { loginMenu } from "@/api/loginMenu";
import { storeUserFindListByLinkMobile } from "@/api/storeUser";
import { createMenuListWithStore, createMenuListWithCompany } from "@/libs/login";
export default {
  data() {
    return {
      Loading: "value",
      phoneNumber: "",
      userAccountType: "",
      userLoginType: "",
      storeUserId: "",
      storeCode: "",
      storeUserList: "",
      chainStoreInfo: []
    };
  },
  components: {
    LoginForm
  },
  methods: {
    ...mapActions(["handleLogin", "getUserInfoNew", "getMenuList"]),
    handleSubmit({ phone, pwd }) {
      this.phoneNumber = phone;
      window.Loading = this.$myLoading({ content: "正在登录…" });
      this.handleLogin({ phone, pwd })
        .then(res => {
          const { code, data, message } = res;
          if (code == 200) {
            setToken(data);
            localStorage.setItem('password', pwd);
            this.getUserInfo();
          } else {
            window.Loading.close();
            this.$Message.error(message);
          }
        },
        reject => {
          window.Loading.close();
          if (reject.message == "Network Error") {
            this.$Message.error({ content: "服务器开小差了~", duration: 2000 });
          } else {
            this.$Message.error(reject.message);
          }
        }
        );
    },
    // 查询登录账号信息列表
    getUserInfo() {
      this.getUserInfoNew({}).then(res => {
        const { code, data, message } = res;
        if (code == 200) {
          window.Loading.close();
          this.phoneLoginHandle(data);
        } else {
          window.Loading.close();
          this.$Message.error(message);
        }
      });
    },
    // 处理登录流程
    phoneLoginHandle(data) {
      let userLoginType = data.userLoginType;
      if (userLoginType != null) {
        // userLoginType有值，后端已经判断好了应该登录的账户类型
        if (userLoginType == 'store') {
          // 清空门店列表
          localStorage.setItem('storeList', []);
          this.loginWithStoreType(data.storeUserId, data.storeUserList[0]);
        } else {
          // 清空门店列表
          localStorage.setItem('storeList', []);
          this.loginWithCompanyType(data.chainStoreInfo.userId, data.chainStoreInfo);
        }
        return;
      }

      let userAccountType = data.userAccountType;
      if (userAccountType == 'store') {
        // 单店账户
        let storeUserList = data.storeUserList;
        if (storeUserList == null) {
          this.$Message.error('当前单店账户无门店数据');
        } else {
          if (storeUserList.length > 0) {
            let singleStoreList = this.flatteningSingleStoreList(storeUserList);
            localStorage.setItem('storeList', JSON.stringify(singleStoreList));
            store.commit('setStoreList', singleStoreList);
            this.toStoreList('store');
          } else {
            this.$Message.error('当前单店账户无门店数据');
          }
        }
      } else {
        // 连锁账户
        let chainStoreInfo = data.chainStoreInfo;
        if (chainStoreInfo == null) {
          this.$Message.error('当前连锁账户无门店数据');
        } else {
          let chainStoreList = this.flatteningChainStoreList(chainStoreInfo);
          if (chainStoreList.length > 1) {
            localStorage.setItem('storeList', JSON.stringify(chainStoreList));
            store.commit('setStoreList', chainStoreList);
            this.toStoreList('company');
          } else {
            this.loginWithCompanyType(data.chainStoreInfo.userId, data.chainStoreInfo);
          }
        }
      }
    },
    // 单店账户门店列表
    flatteningSingleStoreList(storeUserList) {
      for (let j = 0; j < storeUserList.length; j++) {
        var storeInfo = storeUserList[j];
        storeInfo.accountType = 'store';
      }
      return storeUserList;
    },
    // 扁平化连锁门店列表
    flatteningChainStoreList(chainStoreInfo) {
      var tempList = [];
      if (chainStoreInfo != null) {
        tempList.push(
          {
            id: chainStoreInfo.userId,
            userId: chainStoreInfo.userId,
            loginName: chainStoreInfo.loginName,
            userPhone: chainStoreInfo.userPhone,
            storeName: chainStoreInfo.storeName,
            storeCodeList: chainStoreInfo.storeCodeList,
            accountType: 'company'
          }
        );

        let storeInfoList = chainStoreInfo.storeInfoList
        for (let j = 0; j < storeInfoList.length; j++) {
          var storeInfo = storeInfoList[j];
          storeInfo.accountType = 'store';
          tempList.push(storeInfo);
        }
      }
      return tempList;
    },
    // 获取角色列表
    async getUserIdList() {
      // const Loading = this.$myLoading({ content: "正在获取角色列表…" });
      const { data, status, message } = await storeUserFindListByLinkMobile(this.phoneNumber);
      if (status == 200) {
        if (data.data == null || data.data == undefined) {
          window.Loading.close();
          this.$Message.error(message);
        } else {
          if (data.data.length > 0) {
            if (data.data.length > 1) {
              // this.toStoreList();
            } else {
              // this.loginMenu(data.data[0].roleId);
            }
          } else {
            window.Loading.close();
            this.$Message.error(message);
          }
        }
      } else {
        window.Loading.close();
        this.$Message.error(message);
      }
    },
    // 进入门店列表页
    toStoreList(accountType) {
      this.$router.push({
        name: 'selectStore',
        query: {
          accountType: accountType
        }
      });
    },
    tohome() {
      // this.Loading.close();
      this.$router.push({
        // path: '/' + this.$config.homeName
        name: this.$config.homeName
      });
      // window.Loading.close();
    },
    GoRegister() {
      this.$router.push({
        name: "register"
      });
    },
    resetPwd() {
      this.$router.push({
        name: "password"
      });
    },
    loginWithStoreType(userId, storeInfo) {
      loginMenu().then(res => {
        let storeMenuList = res.data.data;
        createMenuListWithStore(userId, storeInfo, storeMenuList);
        this.tohome();
      });
    },
    loginWithCompanyType(userId, storeInfo) {
      createMenuListWithCompany(userId, storeInfo);
      this.tohome();
    }
  }
};
</script>

<style>
.f1{
  float:left!important;
}
.fr{
  float: right!important;
}
.common {
  cursor: pointer;
  font-size: 10px;
  color: #c3c3c3;
  margin-top: -15px;
}
.common:hover {
  color: rgb(97, 87, 81);
  text-decoration: underline;
}
</style>
